package com.csw.android.ffmpegtest.media.play.base

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.csw.android.dev_utils.handler.MainHandler

open class BasePlayer constructor(
    val fp: String,
    val lifecycleOwner: LifecycleOwner,
    val listener: IPlayerListener
) : IPlayer, LifecycleObserver {
    protected var state = PlayState.INIT
    protected var working = false
    protected val mainHandler = MainHandler()

    init {
        lifecycleOwner.lifecycle.addObserver(this)
    }

    override fun start(): Boolean {
        return state == PlayState.INIT
    }

    override fun stop(): Boolean {
        return state == PlayState.RUNNING
    }

    override fun getFilePath(): String {
        return fp
    }

    override fun getPlayState(): PlayState {
        return state
    }

    protected open fun release() {

    }

    //Lifecycle-------------------------------------------------------------------------------------
    /**
     * 监听界面的生命周期，若界面销毁，则自动结束录制
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onViewDestroy() {
        stop()
    }

    //通知方法---------------------------------------------------------------------------------------
    protected open fun onStart() {
        state = PlayState.STARTED
        mainHandler.post {
            listener.onStarted(this)
        }
    }

    protected open fun onRunning(total: Long, curr: Long) {
        state = PlayState.RUNNING
        mainHandler.post {
            listener.onRunning(this, total, curr)
        }
    }

    protected open fun onComplete() {
        state = PlayState.COMPLETED
        release()
        mainHandler.post {
            listener.onCompleted(this)
        }
    }

    protected open fun onError(exception: Exception) {
        state = PlayState.ERROR
        release()
        mainHandler.post {
            listener.onError(this, exception)
        }
    }
}